package com.nikanbujian.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nikanbujian.reggie.dto.DishDto;
import com.nikanbujian.reggie.entity.Dish;
import com.nikanbujian.reggie.entity.DishFlavor;
import com.nikanbujian.reggie.mapper.DishMapper;
import com.nikanbujian.reggie.service.IDishFlavorService;
import com.nikanbujian.reggie.service.IDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-20
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    IDishFlavorService iDishFlavorService;
    @Override
    public void saveDish(DishDto dto) {
        this.save(dto);
        List<DishFlavor> flavors = dto.getFlavors();
        Long id = dto.getId();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        iDishFlavorService.saveBatch(flavors);
    }

    @Override
    public void updateDish(DishDto dto) {
        this.updateById(dto);
        List<DishFlavor> flavors = dto.getFlavors();
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dto.getId()!=null,DishFlavor::getDishId,dto.getId());
        iDishFlavorService.remove(lambdaQueryWrapper);
        flavors=flavors.stream().map((item) -> {
            item.setDishId(dto.getId());
            return item;
        }).collect(Collectors.toList());
        iDishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getDishDto(Long id) {
        Dish dish = this.getById(id);
        DishDto dto = new DishDto();
        BeanUtils.copyProperties(dish,dto);
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = iDishFlavorService.list(lambdaQueryWrapper);
        dto.setFlavors(list);
        return dto;
    }
}
